package cn.jly.mp.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.HashMap;

/**
 * @author lanyangji
 * @description
 * @date 2020/11/24 下午 3:43
 */
@Configuration
public class DruidConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    @Bean
    public ServletRegistrationBean<StatViewServlet> servletRegistrationBean() {
        final ServletRegistrationBean<StatViewServlet> registrationBean =
                new ServletRegistrationBean<>(new StatViewServlet());

        final HashMap<String, String> initParamMap = new HashMap<>();
        initParamMap.put("loginUsername", "admin");
        initParamMap.put("loginPassword", "123456");
        initParamMap.put("allow", "127.0.0.1");

        registrationBean.setInitParameters(initParamMap);
        registrationBean.setUrlMappings(Collections.singletonList("/druid/*"));

        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<WebStatFilter> filterFilterRegistrationBean() {
        final FilterRegistrationBean<WebStatFilter> registrationBean =
                new FilterRegistrationBean<>(new WebStatFilter());

        final HashMap<String, String> initParamMap = new HashMap<>();
        initParamMap.put("exclusions", "/druid/*");

        registrationBean.setInitParameters(initParamMap);
        registrationBean.setUrlPatterns(Collections.singleton("/*"));

        return registrationBean;
    }
}
